package server1;


import constants.Constants;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Locale;

public class Response implements ServletResponse {
    private OutputStream output;
    private Request request;
    public Response(OutputStream output) {
        this.output = output;
    }
    public void setRequest(Request request) {
        this.request = request;
    }
    public void sendStaticResource() {
        FileInputStream fis = null;
        try {
            File file = new File(Constants.WEB_ROOT + request.getUri());
            if (file.exists() && file.isFile()) {
                PrintStream print = new PrintStream(output);
                print.println("HTTP/1.1 200 OK");
                print.println("Content-Type: text/html; charset=utf-8");
                print.println("Content-length: " + file.length());
                print.println();

                fis = new FileInputStream(file);
                byte[] buffer = new byte[2048];
                int len = 0;
                while ((len = fis.read(buffer)) != -1) {
                    print.write(buffer, 0, len);
                }
            } else {
                output.write(Constants.ERROR_MESSAGE.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void send404NotFound() {
        try {
            output.write(Constants.ERROR_MESSAGE.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void send500ServerError() {
        try {
            output.write(Constants.SERVER_ERROR_MESSAGE.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public String getCharacterEncoding() {
        return null;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(output, true);
    }

    @Override
    public void setContentLength(int i) {

    }

    @Override
    public void setContentType(String s) {

    }

    @Override
    public void setBufferSize(int i) {

    }

    @Override
    public int getBufferSize() {
        return 0;
    }

    @Override
    public void flushBuffer() throws IOException {

    }

    @Override
    public void resetBuffer() {

    }

    @Override
    public boolean isCommitted() {
        return false;
    }

    @Override
    public void reset() {

    }

    @Override
    public void setLocale(Locale locale) {

    }

    @Override
    public Locale getLocale() {
        return null;
    }
}
